-- Server Side --

-- Creates the Database
if sql.TableExists("apple_tdm_teamcreation22") then
MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamDB",Color(255,255,255),"] Database 'apple_tdm_teamcreation22' Already Exists!\n")
	else
		if (!sql.TableExists("apple_tdm_teamcreation22")) then
			local Query = "CREATE TABLE apple_tdm_teamcreation22 ( ID int, Name varchar(255), CRed varchar(255), CGreen varchar(255), CBlue varchar(255), Models text, Weapons text )"
			local Result = sql.Query(Query)
			if (sql.TableExists("apple_tdm_teamcreation22")) then
				--MsgN("[TDM-TeamCreation] Successfully Created Database 'apple_tdm_teamcreation22'!")
				MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamDB",Color(255,255,255),"] Successfully Created Database 'apple_tdm_teamcreation22'!\n")
			else
				--MsgN("[TDM-TeamCreation] Database 'apple_tdm_teamcreation22' Was Not Created!")
				MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamDB",Color(255,255,255),"] Database 'apple_tdm_teamcreation22' Was Not Created!\n")
				MsgN( sql.LastError( Result ) )
			end	
		end
end


-- Adds Teams to the Database
function TDMCreateTeam(len, ply)
if !ply:IsSuperAdmin() then return end
-- if args == nil then 
--	MsgN("[TDM-TeamCreation] Variable Are Missing!")
-- return end
-- ClearTeams = {}
-- for k, v in pairs(net.ReadTable()) do
-- table.insert(ClearTeams,v.Teams)
-- end

local TeamName = net.ReadString( )
local TTColor = net.ReadTable()
local Models = net.ReadString( )
local Weapons = net.ReadString( )

local LastTeamIDCreated = tonumber(sql.QueryValue( "SELECT ID FROM apple_tdm_teamcreation22 ORDER BY ID DESC LIMIT 1" ))
if LastTeamIDCreated == nil then
	LastTeamIDCreated = 0
end

local LastTeamIDCreated = (LastTeamIDCreated + 1)
	--MsgN("[TDM-TeamCreation] Team Was Created Successfully, TeamID: "..LastTeamIDCreated)
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamAdd",Color(255,255,255),"] Team Was Created Successfully, TeamID: ",Color(0,255,0),""..LastTeamIDCreated.."\n")
	sql.Query( "INSERT INTO apple_tdm_teamcreation22 (`ID`, `Name`, `CRed`, `CGreen`, `CBlue`, `Models`, `Weapons`) VALUES ('"..tonumber(LastTeamIDCreated).."', '"..TeamName.."', '"..TTColor.r.."', '"..TTColor.g.."', '"..TTColor.b.."', '"..Models.."', '"..Weapons.."' ) ")
AutoFixTeamID()

end
net.Receive("GetTeamListData55", TDMCreateTeam)
--concommand.Add( "TDMCreateTeam", TDMCreateTeam )


-- Checks Teams on the Database
function TDMCheckTeam(ply, cmds, args)
if tonumber(args[1]) == nil then return end

local GetTeamInfo = sql.Query( "SELECT * FROM apple_tdm_teamcreation22 WHERE ID = "..tonumber(args[1]).."" )
if !GetTeamInfo then 
	--MsgN("[TDM-TeamCheck] Team Does Not Exist!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamCheck",Color(255,255,255),"] Team Does Not Exist!\n")
return end
for k, v in pairs( GetTeamInfo ) do
	MsgN("--S--T--A--R--T--")
	MsgN("ID: "..v['ID'])
	MsgN("Name: "..v['Name'])
	MsgN("Color: "..v['CRed']..","..v['CGreen']..","..v['CBlue'])
	MsgN("Models: "..v['Models'])
	MsgN("Weapons: "..v['Weapons'])
	MsgN("---E----N----D---")
end
end
concommand.Add( "TDMCheckTeam", TDMCheckTeam )


-- Checks Entries on the Database
function TDMExistEntry(ply, cmds, args)
local GetTableRows = sql.QueryValue( "SELECT COUNT(*) FROM apple_tdm_teamcreation22" )
	--MsgN("[TDM-CheckEntries] "..GetTableRows.." entries exist in 'apple_tdm_teamcreation22'")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamCheckCount",Color(255,255,255),"] ",Color(0,255,0),""..GetTableRows.."",Color(255,255,255)," entries exist in 'apple_tdm_teamcreation22'\n")
end
concommand.Add( "TDMExistEntry", TDMExistEntry )


-- Edits Teams
function TDMEditTeamsD(len, ply)
if !ply:IsSuperAdmin() then return end
args = net.ReadString( )
args2 = net.ReadString( )
if tonumber(args) == nil then return end

TTColor = net.ReadTable()

local GetTeamEditInfo = sql.Query( "SELECT * FROM apple_tdm_teamcreation22 WHERE ID = "..tonumber(args).."" )
if !GetTeamEditInfo then 
	--MsgN("[TDM-EditTeam] Team Does Not Exist!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamEdit",Color(255,255,255),"] Team Does Not Exist!\n")
return end

local EditTeamsInfo = sql.Query( "UPDATE apple_tdm_teamcreation22 SET Name = '"..tostring(args2).."', CRed = '"..TTColor.r.."', CGreen = '"..TTColor.g.."', CBlue = '"..TTColor.b.."' WHERE ID = '"..tonumber(args).."'" )
if !EditTeamsInfo then
AutoFixTeamID()
	for k, v in pairs(player.GetAll()) do -- Just in case we delete a team has players on it, we want to switch them to something else
		if v:Team() == tonumber(args) then
		umsg.Start("apple_tdm_editnotice", v)
		umsg.End()
		end
	end
end
end
net.Receive("GetTeamListData229", TDMEditTeamsD)



-- Edits Models That are on the Database
function TDMModelTeams(len, ply)
if !ply:IsSuperAdmin() then return end
args = net.ReadString( )
if tonumber(args) == nil then return end

ClearModels = {}
for k, v in pairs(net.ReadTable()) do
table.insert(ClearModels,v.Models)
end

local GetTeamEditInfo = sql.Query( "SELECT * FROM apple_tdm_teamcreation22 WHERE ID = "..tonumber(args).."" )
if !GetTeamEditInfo then 
	--MsgN("[TDM-EditTeam] Team Does Not Exist!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamEdit",Color(255,255,255),"] Team Does Not Exist!\n")
return end

local EditTeamsInfo = sql.Query( "UPDATE apple_tdm_teamcreation22 SET Models = '"..tostring(string.Implode(",", ClearModels)).."' WHERE ID = '"..tonumber(args).."'" )
if !EditTeamsInfo then
	for k, v in pairs(player.GetAll()) do -- Just in case we delete a team has players on it, we want to switch them to something else
		if v:Team() == tonumber(args) then
		umsg.Start("apple_tdm_editnotice", v)
		umsg.End()
		end
	end
end
AutoFixTeamID()
end
net.Receive("GetModelListData2", TDMModelTeams)


-- Edit Weapons That are on the Database
function TDMWeaponTeams(len, ply)
if !ply:IsSuperAdmin() then return end
args = net.ReadString( )
if tonumber(args) == nil then return end

ClearWeapons = {}
for k, v in pairs(net.ReadTable()) do
table.insert(ClearWeapons,v.Weapons)
end

local GetTeamEditInfo = sql.Query( "SELECT * FROM apple_tdm_teamcreation22 WHERE ID = "..tonumber(args).."" )
if !GetTeamEditInfo then 
	--MsgN("[TDM-EditTeam] Team Does Not Exist!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamEdit",Color(255,255,255),"] Team Does Not Exist!\n")
return end

local EditTeamsInfo = sql.Query( "UPDATE apple_tdm_teamcreation22 SET Weapons = '"..tostring(string.Implode(",", ClearWeapons)).."' WHERE ID = '"..tonumber(args).."'" )
if !EditTeamsInfo then
	for k, v in pairs(player.GetAll()) do -- Just in case we delete a team has players on it, we want to switch them to something else
		if v:Team() == tonumber(args) then
		umsg.Start("apple_tdm_editnotice", v)
		umsg.End()
		end
	end
end
AutoFixTeamID()
end
net.Receive("GetWeaponListData55", TDMWeaponTeams)



-- Checks All Data on the Database
function TDMAllEntries(ply, cmds, args)
local GetTeamInfoAll = sql.Query( "SELECT * FROM apple_tdm_teamcreation22" )
if !GetTeamInfoAll then 
	--MsgN("[TDM-CheckAll] Teams Do Not Exist!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamCheckAll",Color(255,255,255),"] Teams Do Not Exist!\n")
return end
for k, v in pairs( GetTeamInfoAll ) do
	MsgN("--S--T--A--R--T--")
	MsgN("ID: "..v['ID'])
	MsgN("Name: "..v['Name'])
	MsgN("Color: "..v['CRed']..","..(v['CGreen'])..","..v['CBlue'])
	MsgN("Models: "..v['Models'])
	MsgN("Weapons: "..v['Weapons'])
	MsgN("---E----N----D---")
end
end
concommand.Add( "TDMAllEntries", TDMAllEntries )



-- Deletes Teams on the Database
function TDMDeleteTeam(len, ply)
if !ply:IsSuperAdmin() then return end
args = net.ReadString( )
if tonumber(args) == nil then return end

local GetTeamName = sql.QueryValue( "SELECT Name FROM apple_tdm_teamcreation22 WHERE ID = "..args.."" ) -- Will check to see if team even exists
if GetTeamName == nil then 
	--MsgN("[TDM-TeamDelete] Team Does Not Exist!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamDelete",Color(255,255,255),"] Team Does Not Exist!\n")
return end

local GetDeleteInfo = sql.Query( "DELETE FROM apple_tdm_teamcreation22 WHERE ID = "..args.."" ) -- Attempted to delete the team
if !GetDeleteInfo then -- If team is deleted correctly, then it will run this fuctions
team.SetScore(args, 0)
	for k, v in pairs(player.GetAll()) do -- Just in case we delete a team has players on it, we want to switch them to something else
		if v:Team() == tonumber(args) then
		umsg.Start("apple_tdm_teamdeletenotice", v)
		umsg.End()
			ChooseTeam(v)
		end
	end
	--MsgN("[TDM-TeamDelete] "..GetTeamName.." Has Been Successfully Deleted!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-TeamDelete",Color(255,255,255),"] ",Color(0,255,0),""..GetTeamName.."",Color(255,255,255)," Has Been Successfully Deleted!\n")
	AutoFixTeamID()
return end
end
net.Receive("GetTeamListData56", TDMDeleteTeam)



-- Fix Team Index
function TDMFixTeams(ply, cmds, args)
local AutoFixID = sql.Query( "SELECT * FROM apple_tdm_teamcreation22" )
	if !AutoFixID then return end
			umsg.Start("apple_tdm_resetclienttable")
			umsg.End()
		for k, v in pairs( AutoFixID ) do -- This will update the index IDs for teams in the database
			sql.Query( "UPDATE apple_tdm_teamcreation22 SET ID = "..k.." WHERE ID = "..v['ID'].."" )
			--MsgN("[TDM-AutoFixIndex] Team: "..v['Name'].."("..k..") have been repaired!")
			MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-FixTeamIndex",Color(255,255,255),"] Team: ",Color(0,255,0),""..v['Name'].."",Color(255,255,255),"(",Color(0,0,255),""..k.."",Color(255,255,255),") have been repaired!\n")
			/*
			umsg.Start("apple_tdm_teamcreation232")
				umsg.Short(k)
				umsg.String(v['Name'])
			umsg.End()
			*/
		end
	timer.Simple(0.25, function()
		CreateTeams()
	end)
end
concommand.Add( "TDMFixTeams", TDMFixTeams )



-- Auto Fix Team Index
if sql.TableExists("apple_tdm_teamcreation22") then
	function AutoFixTeamID()
		local GetAutoFixID = sql.Query( "SELECT * FROM apple_tdm_teamcreation22" )
		if !GetAutoFixID then return end
			umsg.Start("apple_tdm_resetclienttable")
			umsg.End()
			for k, v in pairs( GetAutoFixID ) do -- This will automatically update the index IDs for teams in the database
				sql.Query( "UPDATE apple_tdm_teamcreation22 SET ID = "..k.." WHERE ID = "..v['ID'].."" )
			--MsgN("[TDM-AutoFixIndex] Team: "..v['Name'].."("..k..") have been repaired!")
			MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-AutoFixTeamIndex",Color(255,255,255),"] Team: ",Color(0,255,0),""..v['Name'].."",Color(255,255,255),"(",Color(0,0,255),""..k.."",Color(255,255,255),") have been repaired!\n")
			/*
			umsg.Start("apple_tdm_teamcreation232")
				umsg.Short(k)
				umsg.String(v['Name'])
			umsg.End()
			*/
			end
	timer.Simple(0.25, function()
		CreateTeams()
		CreateSTList()
	end)
	end
AutoFixTeamID()
end